<template>
  <div>
    <h1>0.1.0版本</h1>
    <div>
      <el-button @click="sendNotification">发送系统通知</el-button>
      <el-button @click="callCppDll">调用C++ DLL</el-button>
      <el-button @click="callCsDll">调用C# DLL</el-button>
    </div>
    <div>
      <el-button @click="querySqlite">调用Sqlite</el-button>
    </div>
    <div>
      <el-input
        type="textarea"
        placeholder="请输入内容"
        v-model="textarea"
        maxlength="30"
        show-word-limit
      >
      </el-input>
      <el-button @click="writeToFile">将内容写入文件</el-button>
      <el-button @click="readFileContent">读取中的内容文件</el-button>
      <div>{{fileContent}}</div>
    </div>
    <div>
      <el-button @click="execTerminal">执行命令行</el-button>
    </div>
    <div>
      <el-button @click="checkUpdate">检查更新</el-button>
    </div>
  </div>
</template>
<script>
import db from '../utils/sqlite3Db'

import { exec } from 'child_process'
const { ipcRenderer } = require('electron')
const ffi = require('ffi-napi')
const pathUtil = require('../utils/pathUtil.js')
const fs = require('fs')
ipcRenderer.on('message', (event, text) => {
  console.log(text)
})
ipcRenderer.on('error', (event, text) => {
  console.log('error : ' + text)
})
// 注意：“downloadProgress”事件可能存在无法触发的问题，只需要限制一下下载网速就好了
ipcRenderer.on('downloadProgress', (event, progressObj) => {
  console.log(progressObj.percent || 0)
})
ipcRenderer.on('isUpdateNow', () => {
  ipcRenderer.send('isUpdateNow')
})
let cpplib
let edge
let invoke
if (process.platform === 'darwin') {
  // 在使用libdemo的时候最好自己编译下cpp，命令gcc -g -shared  demo.cpp -o libdemo.dylib
  cpplib = ffi.Library(pathUtil.getAppResourcePath('dll/libdemo'), {
    Add: ['double', ['double', 'double']]
  })
} else if (process.platform === 'win32') {
  // 只在windows平台下加载
  edge = require('electron-edge-js')
  invoke = edge.func({
    assemblyFile: pathUtil.getAppResourcePath('dll/electronedge.dll'),
    typeName: 'electronedge.Class1',
    methodName: 'Invoke'
  })

  cpplib = ffi.Library(pathUtil.getAppResourcePath('dll/MyDLL'), {
    Add: ['float', ['float', 'float']],
    Hello: ['string', []],
    StrLength: ['int', ['string']]
  })
}
export default {
  name: 'DemoTest',
  data () {
    return {
      result: '',
      textarea: '',
      fileContent: ''
    }
  },
  methods: {
    sendNotification () {
      const myNotification = new Notification('标题', {
        body: '通知正文内容'
      })
      myNotification.onclick = () => {
        console.log('通知被点击')
      }
    },
    callCppDll () {
      // dll和dylib提供了不同的方法，所以在这儿不能通用，但是写了各自的调用方法
      if (process.platform === 'win32') {
        console.log('fii.Library Hello result:', cpplib.Hello())
        console.log('fii.Library Add result:', cpplib.Add(1, 2))
        console.log('fii.Library Add result:', cpplib.StrLength('hello world'))
      }
      if (process.platform === 'darwin') {
        console.log(cpplib.Add(12345, 54321))
      }
    },
    callCsDll () {
      const _this = this
      if (process.platform === 'win32') {
        invoke('这是自定义字符串', function (err, val) {
          if (err) throw err
          console.log(val)
          _this.result = val
          _this.$notify.info({
            title: '提示',
            message: '调用C# 返回的结果：' + val
          })
        })
      } else {
        this.$notify.error({
          title: '错误',
          message: '此功能为windows专属功能，mac无法使用'
        })
      }
    },
    showInfoNotify (message) {
      this.$notify.info({
        title: '提示',
        message: message
      })
    },
    writeToFile () {
      fs.writeFile(pathUtil.getAppResourcePath('runtime/file.txt'), this.textarea, 'utf8', function (error) {
        if (error) {
          console.log('写入失败')
          console.log(error)
          return false
        }
        console.log('写入成功')
      })
    },
    readFileContent () {
      const _this = this
      fs.readFile(pathUtil.getAppResourcePath('runtime/file.txt'), function (error, data) {
        if (error) {
          console.log(error)
          return false
        }
        _this.fileContent = data.toString()
        console.log(data.toString())
      })
    },
    querySqlite () {
      db.all('select * from test', function (err, res) {
        if (!err) {
          console.log(JSON.stringify(res))
        } else {
          console.log(err)
        }
      })
    },
    execTerminal () {
      const iconv = require('iconv-lite')
      // 任何你期望执行的cmd命令，ls都可以
      const cmdStr = 'ipconfig'
      // 执行cmd命令的目录，如果使用cd xx && 上面的命令，这种将会无法正常退出子进程
      const cmdPath = pathUtil.getAppResourcePath('')

      // 执行命令行，如果命令不需要路径，或就是项目根目录，则不需要cwd参数：
      const workerProcess = exec(cmdStr, { cwd: cmdPath, encoding: 'GBK' })
      // 不受child_process默认的缓冲区大小的使用方法，没参数也要写上{}：workerProcess = exec(cmdStr, {})

      // 打印正常的后台可执行程序输出
      workerProcess.stdout.on('data', function (data) {
        console.log('stdout: ' + iconv.decode(data, 'GBK'))
        // console.log('stdout: ' + data)
      })

      // 打印错误的后台可执行程序输出
      workerProcess.stderr.on('data', function (data) {
        console.log('stderr: ' + iconv.decode(data, 'GBK'))
        // console.log('stderr: ' + data)
      })

      // 退出之后的输出
      workerProcess.on('close', function (code) {
        console.log('out code：' + code)
      })
    },
    checkUpdate () {
      ipcRenderer.send('checkForUpdate')
    }
  }
}
</script>

<style scoped>

</style>
